package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public ResultInfo login(String username, String password) {
        //根据用户名查询
        Employee employee = employeeMapper.findByUsername(username);
        //判断账号是否存在
        if (employee == null) {
            return ResultInfo.error("该用户不存在");
        }
        //加密密码
        String md5 = SecureUtil.md5(password);
        //判断密码是否正确
        if (!md5.equals(employee.getPassword())) {
            return ResultInfo.error("密码有误！");
        }
        //判断账号状态
        if (employee.getStatus() != 1) {
            return ResultInfo.error("该用户涉嫌违规，已被封禁，请联系客服");
        }
        return ResultInfo.success(employee);
    }

    @Override
    public List<Employee> findlist(String name) {
        return employeeMapper.findList(name);
    }
    //添加
    @Override
    public void save(Employee employee) {
        //补全数据
        //雪花id
        employee.setId(IdUtil.getSnowflake(1, 1).nextId());
        //MD5密码
        employee.setPassword(SecureUtil.md5(Constant.INIT_PASSWORD));
        //创建人，更新人，双剑时间，更新时间
      /*  employee.setUpdateTime(new Date());
        employee.setCreateTime(new Date());
        employee.setUpdateUser(1L);
        employee.setCreateUser(1L);*/
        //状态
        employee.setStatus(1);
        employeeMapper.save(employee);
    }

    @Override
    public Employee findById(Long id) {
        Employee employee = employeeMapper.selectById(id);
        return employee;
    }

    @Override
    public void update(Employee employee) {
        employeeMapper.updateById(employee);
    }
}
